package com.iexbuy.ihg.ui.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.navisdk.util.common.StringUtils;
import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.entity.CoinSum;
import com.iexbuy.ihg.entity.CoinSumResponse;
import com.iexbuy.ihg.entity.LuckUserObject;
import com.iexbuy.ihg.entity.ShopCenter;
import com.iexbuy.ihg.entity.YunDealObject;
import com.iexbuy.ihg.entity.YunDealObjectResponse;
import com.iexbuy.ihg.entity.YunItemListObject;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.utils.DateTools;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.iexbuy.ihg.utils.ToastUtils;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnLongClick;

import java.util.HashMap;


public class YunGuoOrderConfirmFragment extends BaseFragment {

	private static YunGuoOrderConfirmFragment homeFragmentInstent;

	@ViewInject(R.id.msgListLayout)
	private PullToRefreshLayout msgListRefreshLayout;
	@ViewInject(R.id.listView)
	private ListView listView;

	@ViewInject(R.id.productIcon)
	private ImageView productIcon;
	@ViewInject(R.id.productName)
	private TextView productName;
	@ViewInject(R.id.dealTime)
	private TextView dealTime;
	@ViewInject(R.id.priceCoin)
	private TextView priceCoin;
	@ViewInject(R.id.buyNumber)
	private EditText buyNumber;
	@ViewInject(R.id.orderDetail)
	private TextView orderDetail;
	@ViewInject(R.id.remindCount)
	private TextView remindCount;
	@ViewInject(R.id.coinBalance)
	private TextView coinBalance;
	@ViewInject(R.id.specialCoinBalance)
	private TextView specialCoinBalance;
	@ViewInject(R.id.minusBtn)
	private Button minusBtn;
	@ViewInject(R.id.addBtn)
	private Button addBtn;
	@ViewInject(R.id.coinLayout)
	private RelativeLayout coinLayout;
	@ViewInject(R.id.specialCoinLayout)
	private LinearLayout specialCoinLayout;

	private static YunItemListObject yunItemListObject;
	private static String areaCode;
	private String buyNo;

	private int number=1;

	private Handler handler = new Handler();
	public boolean isOnLongClick=false;
	private MiusThread miusThread;
	private PlusThread plusThread;
	private CoinSum coinSum;



	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_yunguo_order_confirm, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		getCoinSum();
		mBaseActivity.setTitle(getResources().getString(R.string.yun_guo_order_confirm));
		mBaseActivity.setTitleLayoutVisibility(true);
		mBaseActivity.setHomeActivity(false);

	}

	private void initBtnNumber() {
		Editable etext = buyNumber.getText();
		Selection.setSelection(etext, etext.length());

		buyNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				if (hasFocus) {
					String str = buyNumber.getText().toString();

					Selection.setSelection(buyNumber.getText(), buyNumber.getText().length());
					buyNumber.setSelectAllOnFocus(true);
				} else if (StringUtil.isBlank(buyNumber.getText().toString())) {
					buyNumber.setText("1");

				}
			}
		});
		buyNumber.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				if (!buyNumber.getText().toString().equals("")) {
					priceCoin.setText(String.valueOf(Integer.valueOf(buyNumber.getText().toString()) * 10));
					number = Integer.parseInt(buyNumber.getText().toString());
				} else {
					priceCoin.setText("0");
				}

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (!buyNumber.getText().toString().equals("")) {
					priceCoin.setText(String.valueOf(Integer.valueOf(buyNumber.getText().toString()) * 10));
					if (Integer.parseInt(buyNumber.getText().toString()) < (Integer.valueOf(yunItemListObject.getRequiredTotalNumber()) - Integer.valueOf(yunItemListObject.getAttandanceNumber()))) {
						number = Integer.parseInt(buyNumber.getText().toString());
					}
				} else {
					priceCoin.setText("0");
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (!buyNumber.getText().toString().equals("")) {
					priceCoin.setText(String.valueOf(Integer.valueOf(buyNumber.getText().toString()) * 10));
					if (areaCode == null) {
						if (Integer.parseInt(priceCoin.getText().toString()) <= coinSum.getCoinTotal() && Integer.parseInt(buyNumber.getText().toString()) <= (Integer.valueOf(yunItemListObject.getRequiredTotalNumber()) - Integer.valueOf(yunItemListObject.getAttandanceNumber()))) {
							number = Integer.parseInt(buyNumber.getText().toString());

						} else {
							ToastUtils.toast(mBaseActivity, "您的金币额度或剩余次数不足,无法参与过多次数,请前往消费商品获取更多金币再来参与活动！");
						}
					} else {
						if (Integer.parseInt(priceCoin.getText().toString()) <= coinSum.getCoinArea() && Integer.parseInt(buyNumber.getText().toString()) <= (Integer.valueOf(yunItemListObject.getRequiredTotalNumber()) - Integer.valueOf(yunItemListObject.getAttandanceNumber()))) {
							number = Integer.parseInt(buyNumber.getText().toString());
						} else {
							ToastUtils.toast(mBaseActivity, "您的专场金币额度或剩余次数不足,无法参与过多次数,请前往消费商品获取更多金币再来参与活动！");
						}
					}
				} else {
					priceCoin.setText("0");
				}
			}
		});
		buyNumber.clearFocus();
	}

	private void getCoinSum() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("userId", App.sPreferences.getUserId());

		if (areaCode!=null){
			paramMap.put("areaCode", areaCode);
		}

		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_COINSUM, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						CoinSumResponse rep = JsonUtils.parseJsonStrToObject(responseInfo.result, CoinSumResponse.class);
						coinSum = rep.getBody();

						initCoinView();
					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});

	}

	@Override
	public void onPause() {
		super.onPause();
		areaCode=null;
	}

	private void initCoinView() {
		if(areaCode==null){
			specialCoinLayout.setVisibility(View.GONE);
			if(coinSum.getCoinTotal()<10){
				String Specialmessage = "您的金币额度<10,无法参与0购活动,请前往消费商品获取金币再来参与活动！";
				initSpecialDialog(Specialmessage);
			}
		}else{
			specialCoinLayout.setVisibility(View.VISIBLE);
			specialCoinBalance.setText(coinSum.getCoinArea() + "金币");
			if(coinSum.getCoinArea()<10){
				String Specialmessage = "您的专场0购金币额度<10,无法参与0购活动,请前往专场消费商品获取金币再来参与活动！";
				initSpecialDialog(Specialmessage);
			}

		}
		coinBalance.setText(coinSum.getCoinTotal() + "金币");
		initBtnNumber();
		initOrderInfo();
		initNumberChange();
	}

	private void initSpecialDialog(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(mBaseActivity);
		builder.setTitle("温馨提醒").setMessage(message)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						YunGuoItemDetailFragment.setIsClosed(true);
						mBaseActivity.finish();
					}
				}).setNegativeButton("取消",new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				YunGuoItemDetailFragment.setIsClosed(false);
			}
		});
		builder.create();
		builder.show();
	}

	private void initNumberChange() {
		minusBtn.setOnTouchListener(new CompentOnTouch());
		addBtn.setOnTouchListener(new CompentOnTouch());
	}
	class CompentOnTouch implements View.OnTouchListener {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (v.getId()) {
				case R.id.minusBtn:
					onTouchChange("mius", event.getAction());
					break;
				case R.id.addBtn:
					onTouchChange("plus", event.getAction());
					break;
			}
			return true;
		}
	}
	private void onTouchChange(String methodName, int eventAction) {
		if ("mius".equals(methodName)) {
			if (eventAction == MotionEvent.ACTION_DOWN) {
				miusThread = new MiusThread();
				isOnLongClick = true;
				miusThread.start();
			} else if (eventAction == MotionEvent.ACTION_UP) {
				if (miusThread != null) {
					isOnLongClick = false;
				}
			} else if (eventAction == MotionEvent.ACTION_MOVE) {
				if (miusThread != null) {
					isOnLongClick = true;
				}
			}
		}
		else if ("plus".equals(methodName)) {
			if (eventAction == MotionEvent.ACTION_DOWN) {
				plusThread = new PlusThread();
				isOnLongClick = true;
				plusThread.start();
			} else if (eventAction == MotionEvent.ACTION_UP) {
				if (plusThread != null) {
					isOnLongClick = false;
				}
			} else if (eventAction == MotionEvent.ACTION_MOVE) {
				if (plusThread != null) {
					isOnLongClick = true;
				}
			}
		}
	}
	class MiusThread extends Thread {
		@Override
		public void run() {
			while (isOnLongClick) {
				try {
					Thread.sleep(200);
					if(number>0){
						number--;
					}
					handler.post(new Runnable() {
						@Override
						public void run() {
							buyNumber.setText(String.valueOf(number));
						}
					});
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				super.run();
			}
		}
	}


	// 加操作
	class PlusThread extends Thread {
		@Override
		public void run() {
			while (isOnLongClick) {
				try {
					Thread.sleep(200);

						if(areaCode==null&&Integer.parseInt(priceCoin.getText().toString()) <= coinSum.getCoinTotal() &&number<(Integer.valueOf(yunItemListObject.getRequiredTotalNumber()) - Integer.valueOf(yunItemListObject.getAttandanceNumber()))){
							if(number==0||coinSum.getCoinTotal()/(number*10)!=1){
								number++;
							}

						}else if(areaCode!=null&&Integer.parseInt(priceCoin.getText().toString()) <= coinSum.getCoinArea() &&number<(Integer.valueOf(yunItemListObject.getRequiredTotalNumber()) - Integer.valueOf(yunItemListObject.getAttandanceNumber()))){
							if(number==0||coinSum.getCoinArea()/(number*10)!=1){
								number++;
							}
						}

					handler.post(new Runnable() {
						@Override
						public void run() {

							buyNumber.setText(String.valueOf(number));
						}
					});

				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				super.run();
			}
		}
	}

	private void initOrderInfo() {
		if (yunItemListObject == null) return;
		App.bitmapUtils.display(productIcon, yunItemListObject.getThumbnailUrl());
		productName.setText("[" + yunItemListObject.getPeriod() + "] " + yunItemListObject.getItemName());
		orderDetail.setText("总共" + yunItemListObject.getRequiredTotalNumber() + "人次 还剩余：" + (Integer.valueOf(yunItemListObject.getRequiredTotalNumber()) - Integer.valueOf(yunItemListObject.getAttandanceNumber())));
		remindCount.setText("" + (Integer.valueOf(yunItemListObject.getRequiredTotalNumber()) - Integer.valueOf(yunItemListObject.getAttandanceNumber())));
		dealTime.setText(DateTools.getCurrentDateTime());
		priceCoin.setText(String.valueOf(Integer.valueOf(buyNumber.getText().toString()) * 10));
		//coinBalance.setText(App.sPreferences.getCoinBalance());

	}

	//点击事件响应
	@OnClick(R.id.submitYunguoBtn)
	public void onSubmitYunguoBtnClick(View view) {
		if (yunItemListObject == null) {
			return;
		}
		buyNo = priceCoin.getText().toString();
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("itemId", yunItemListObject.getItemId());
		paramMap.put("userId", App.sPreferences.getUserId());
		paramMap.put("number", buyNo);
		ServiceHelper.send(mBaseActivity, ServiceHelper.SUBMIT_YUN_GUO_DEAL, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						YunDealObjectResponse rsp = JsonUtils.parseJsonStrToObject(responseInfo.result, YunDealObjectResponse.class);
						if (rsp.getResultCode() != 0) {
							ToastUtils.toast(mBaseActivity, rsp.getResultMessage());
						} else {
							YunDealObject dealObject = rsp.getBody();
							if (dealObject == null) {
								dealObject = new YunDealObject();
							}
							dealObject.setPeriod(yunItemListObject.getPeriod());
							dealObject.setItemName(yunItemListObject.getItemName());

							YunGuoOrderResultFragment.setYunDealObject(dealObject);
							YunGuoOrderResultFragment.setYunItemListObject(yunItemListObject);
							CommUtil.openSingleFragmentActivity(mBaseActivity, YunGuoOrderResultFragment.class);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						ToastUtils.toast(mBaseActivity, msg);
					}
				});
	}
	@OnClick(R.id.specialCoinLayout)
	private void onSpecialCoinLayoutBtn(View v){
		if (areaCode!=null){
			WeDeCoinRecordsFragment.setAreaCode(areaCode);
			WeDeCoinRecordsFragment.setCoinArea(coinSum.getCoinArea());
		}
		CommUtil.openSingleFragmentActivity(mBaseActivity, WeDeCoinRecordsFragment.class);
	}
	public static void setAreaCode(String areaCode) {
		YunGuoOrderConfirmFragment.areaCode = areaCode;
	}

	public static void setYunItemListObject(YunItemListObject yunItemListObject) {
		YunGuoOrderConfirmFragment.yunItemListObject = yunItemListObject;
	}


	/**
	 * @return the homeFragmentInstent
	 */
	public static YunGuoOrderConfirmFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
